package com.siyoumi.app.modules.tmplmsg.admin;

import com.siyoumi.app.entity.WxTmplmsg;
import com.siyoumi.app.sys.service.wxapi.WxApiMp;
import com.siyoumi.app.service.WxTmplmsgService;
import com.siyoumi.config.SysConfig;
import com.siyoumi.controller.AdminApiController;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.component.http.XHttpContext;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/xadmin/tmplmsg/tmplmsg__send")
public class tmplmsg__send
        extends AdminApiController {
    @GetMapping()
    public XReturn index() {
        setPageTitle("模板消息-发送");

        WxTmplmsgService app = WxTmplmsgService.getBean();

        Integer uploadStep = 200;
        if (SysConfig.getIns().isDev()) {
            uploadStep = 2;
        }

        Map<String, Object> data = new HashMap<>();
        data.put("upload_step", uploadStep);
        if (isAdminEdit()) {
            WxTmplmsg entity = app.loadEntity(getID());

            HashMap<String, Object> dataAppend = new LinkedHashMap<>();
            dataAppend.put("id", entity.getKey());
            //
            data = entity.toMap();
            data.putAll(dataAppend);
        }
        getR().setData("data", data);

        return getR();
    }


    @Transactional
    @PostMapping("/batch_send")
    public XReturn send() {
        if (XStr.isNullOrEmpty(getPid())) {
            return EnumSys.MISS_VAL.getR("miss pid");
        }

        String uploadData = input("upload_data");
        if (XStr.isNullOrEmpty(uploadData)) {
            return EnumSys.MISS_VAL.getR("miss upload_data");
        }

        WxTmplmsgService app = WxTmplmsgService.getBean();
        WxApiMp officialAccount = WxApiMp.getIns(XHttpContext.getXConfig());

        List<Map> listMap = XStr.toJsonArr(uploadData);

        Map<String, Object> sendData = app.getSendJson(getPid(), "__openid__", null, null);
        for (Map map : listMap) {
            String openid = (String) map.get("openid");

            Map<String, Object> postData = sendData;
            postData.put("touser", openid);

            officialAccount.sendTemplate(postData);
        }


        return getR();
    }
}
